import { relationalStore } from '@kit.ArkData'
import { history } from '../HistoryDatabase/history'

const STORE_CONFIG = {
  name: 'RdbTest.db', // 数据库文件名
  securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
}
// 建表sql语句
const SQL_CREATE_TABLE_4 = 'CREATE TABLE IF NOT EXISTS HISTORY (ID INTEGER PRIMARY KEY, IMGURL TEXT NOT NULL, TITLE TEXT NOT NULL, AUTHOR TEXT NOT NULL, INTRODUCE TEXT NOT NULL, READNUMBER INTEGER DEFAULT 0, HOT INTEGER DEFAULT 0)'

class HistoryDatabase {
  private contactDataRdbStore: relationalStore.RdbStore

  createNow(context){
    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store)=>{
      if (err) {
        console.error('失败', err);
        return;
      }
      console.info('成功')
      store.executeSql(SQL_CREATE_TABLE_4)
      this.contactDataRdbStore = store;
    })
  }

  // 添加浏览历史信息
  saveNewHistory(imgurl: string, title: string, author: string, introduce: string, readnumber: number, hot: number){
    let valueBookshelf = {
      'IMGURL': imgurl,
      'TITLE': title,
      'AUTHOR': author,
      'INTRODUCE': introduce,
      'READNUMBER': readnumber,
      'HOT': hot
    }

    this.contactDataRdbStore.insert('HISTORY', valueBookshelf, (err, rowId)=>{
      if (err) {
        console.error('存放数据失败', err)
        return;
      }
      console.info('存放数据成功，行ID：', rowId)
    })
  }
  // 查询所有参数
  historyContacts(callback: Function){
    // 创建谓词
    let predicates = new relationalStore.RdbPredicates('HISTORY')
    // 调用query()方法查找数据，返回一个ResultSet结果集
    this.contactDataRdbStore.query(predicates,['ID','IMGURL','TITLE','AUTHOR','INTRODUCE','READNUMBER','HOT'],(err,resultSet)=>{
      if (err) {
        console.error(`Failed to query data. Code:${err.code},message:${err.message}`)
        return
      }
      console.info(`ResultSet column names:${resultSet.columnNames}`)
      console.info(`ResultSet column count:${resultSet.columnNames}`)
      console.info(`ResultSet:${JSON.stringify(resultSet)}`)
      // resultSet是一个数据集合的游标，默认指向第-1个记录，有效的数据从0开始。
      let count: number = resultSet.rowCount
      resultSet.goToFirstRow()
      let result: history[] = []
      for(let i = 0; i < count; i++){
        let tmp: history = {id: '', imgurl: '',title: '', author: '',introduce: '', readNumber: 0, hot: 0}
        tmp.id = resultSet.getString(resultSet.getColumnIndex('ID'))
        tmp.imgurl = resultSet.getString(resultSet.getColumnIndex('IMGURL'))
        tmp.title = resultSet.getString(resultSet.getColumnIndex('TITLE'))
        tmp.author = resultSet.getString(resultSet.getColumnIndex('AUTHOR'))
        tmp.introduce = resultSet.getString(resultSet.getColumnIndex('INTRODUCE'))
        tmp.readNumber = resultSet.getDouble(resultSet.getColumnIndex('READNUMBER'))
        tmp.hot = resultSet.getDouble(resultSet.getColumnIndex('HOT'))
        result[i] = tmp
        resultSet.goToNextRow()
      }
      // 释放数据集的内存
      resultSet.close()
      let flag: boolean = true
      let result2: history[] = []
      let num: number = 0
      for(let i = 0; i < result.length; i++){
        flag = true
        for(let j = i+1; j < result.length; j++){
          if (result[i].imgurl === result[j].imgurl && result[i].title === result[j].title && result[i].author === result[j].author) {
            flag = false
            break
          }
        }
        if (flag) {
          result2[num] = result[i]
          num++
        }
        console.info(`Final result: ${JSON.stringify(result[i])}`)
      }
      // 创建倒序数组
      let result1: history[] = result2.slice().reverse()
      callback(result1)
    })
  }

}
let historyDatabase = new HistoryDatabase()
export default historyDatabase